/**
 * Created by ${PRODUCT_NAME}.
 * User: skylerparr
 * Date: 2/1/11
 * Time: 9:15 AM
 * To change this template use File | Settings | File Templates.
 */
package com.thoughtorigin.display.containers {
import flash.display.DisplayObject;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;

public class DefaultMaskContainer extends EventDispatcher implements MaskedContainer {

    private var _mask: DisplayObject;
    private var _container: Container;

    private var _width: Number = 0;
    private var _height: Number = 0;
    private var _x: Number = 0;
    private var _y: Number = 0;
    private var _isWidthSet: Boolean;
    private var _isHeightSet: Boolean;

    public function DefaultMaskContainer(value: Container) {
        init(value);
    }

    private function init(value:Container):void {
        _container = value;
        _container.addEventListener(ContainerEvent.RAW_CHILDREN_CHANGE, onRawChildrenChange, false, 0, true);
        _container.addEventListener(ContainerEvent.RECALCULATE_BOUNDS, onRawChildrenChange, false, 0, true);
        _mask = new Shape();
        applyMask();
    }

    private function onRawChildrenChange(e: Event):void {
        applyMask();
        dispatchEvent(new LayoutEvent(LayoutEvent.LAYOUT_REFRESH));
    }

    private function applyMask(): void {
        if(!_isWidthSet) {
            _width = _container.rawChildContainer.width;
        }
        if(!_isHeightSet) {
            _height = _container.rawChildContainer.height;
        }
        with(Shape(_mask).graphics) {
            clear();
            beginFill(0, 0);
            drawRect(0,0,_width, _height);
            endFill();
        }
        if(_container.rawContains(_mask)) {
            _container.removeRawChild(_mask);
        }
        _container.addRawChild(_mask);
        _container.mask = _mask;
    }

    public function get mask():DisplayObject {
        return _mask;
    }

    public function set mask(value:DisplayObject):void {
        if(_mask) {
            _container.removeRawChild(_mask);
        }
        _container.addRawChild(_mask);
        _mask = value;
        _container.mask = _mask;
    }

    public function set width(value:Number):void {
        _width = value;
        _isWidthSet = true;
        onRawChildrenChange(null);
    }

    public function get width(): Number {
        return _width;
    }

    public function set height(value:Number):void {
        _height = value;
        _isHeightSet = true;
        onRawChildrenChange(null);
    }

    public function get height(): Number {
        return _height;
    }

    public function get x():Number {
        return _x;
    }

    public function set x(value:Number):void {
        _x = value;
        _mask.x = _x;
    }

    public function get y():Number {
        return _y;
    }

    public function set y(value:Number):void {
        _y = value;
        _mask.y = _y;
    }
}
}
